package com.ben.utils.livedata

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer

/**
 * @author bin.yang
 * @date 2020/1/6
 * @maintainer bin.yang
 * @desc:
 */
fun <T> LiveData<T>.observeOnce(observer: Observer<T>) {
    observeForever(object : Observer<T> {
        override fun onChanged(value: T) {
            observer.onChanged(value)
            removeObserver(this)
        }
    })
}

fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<T>) {
    observe(
        owner,
        object : Observer<T> {
            override fun onChanged(t: T) {
                observer.onChanged(t)
                removeObserver(this)
            }
        }
    )
}

fun <T> LiveData<T>.observeWithEnd(observer: Observer<T>, func: (it: T?) -> Boolean) {
    observeForever(object : Observer<T> {
        override fun onChanged(t: T) {
            observer.onChanged(t)
            if (func(t)) removeObserver(this)
        }
    })
}

fun <T> LiveData<T>.observeWithEnd(owner: LifecycleOwner, observer: Observer<T>, func: (it: T?) -> Boolean) {
    observe(
        owner,
        object : Observer<T> {
            override fun onChanged(t: T) {
                observer.onChanged(t)
                if (func(t)) removeObserver(this)
            }
        }
    )
}

fun <T> LiveData<T>.observeForeverWithEnd(observer: Observer<T>, func: (it: T?) -> Boolean) {
    observeForever(object : Observer<T> {
        override fun onChanged(t: T) {
            observer.onChanged(t)
            if (func(t)) removeObserver(this)
        }
    })
}
